import request from '@/utils/request';
import type { LoginRequest, LoginResponse,  RefreshTokenRequest } from '@/types/auth';
import { User } from '@/types/user';

// 登录
export const login = async (data: LoginRequest): Promise<LoginResponse> => {
  return request.post<LoginResponse>('/api/auth/login', data);
};

// 注册
export const register = async (data: any): Promise<LoginResponse> => {
  return request.post<LoginResponse>('/api/auth/register', data);
};

// 获取当前用户信息
export const getCurrentUser = async (): Promise<User> => {
  return request.post<User>('/api/auth/me');
};

// 刷新token
export const refreshToken = async (data:RefreshTokenRequest) => {
  return request.post<{ token: string }>('/api/auth/refresh',data);
};


/**
 * 退出登录
 */
export const logout = () => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('token');
    window.location.href = '/login';
  }
};

/**
 * 检查是否已登录
 */
export const isLoggedIn = (): boolean => {
  if (typeof window === 'undefined') {
    return false; // SSR环境下默认未登录
  }
  return !!localStorage.getItem('token');
};

/**
 * 获取存储的token
 */
export const getToken = (): string | null => {
  if (typeof window === 'undefined') {
    return null; // SSR环境下返回null
  }
  return localStorage.getItem('token');
};

/**
 * 设置token
 */
export const setToken = (token: string): void => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('token', token);
  }
};

/**
 * 清除token
 */
export const clearToken = (): void => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('token');
  }
};
